<?php
/**
 * Created by PhpStorm.
 * User: wx:wenyi2048
 * Date: 2022/3/18 0018
 * Time: 09:20
 */

namespace app\admin\controller\mk;
/*商品分类管理*/

use app\admin\Controller;
use app\common\service\TypeService;
use think\Db;
use think\Exception;
use think\Loader;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path'), EXT);

class Types extends Controller
{

    use \app\admin\traits\controller\Controller;
    public function index()
    {
        $param = $this->request->param();
        $service = new TypeService();//数据处理
        $dataList = $service->treeList();
        //var_dump($dataList);die();
        $this->view->assign('list',$dataList);
        return $this->view->fetch();
    }

    protected function afterEdit(){
        $vo = $this->view->__get('vo');
        if(@$vo['pid']){
            $pNode = Db::name("MkTypes")->where("id", $vo['pid'])->field("name")->find();
            $vo['pname'] = $pNode['name'];
            $this->view->assign('vo', $vo);
        }
    }

//    protected function overAdd($id){
//        var_dump($id);die();
//    }

    protected function beforeAdd(){
        //父节点和层级
        $id = $this->request->param('id');
        $vo['level'] = 1;
        if($id){//有id 说明不是添加父级（一级）
            $node = Db::name("MkTypes")->where("id", $id)->field("id,level,name")->find();
            $vo['level'] = intval($node['level']) + 1;
            $vo['pid'] = $id;
            $vo['pname'] = $node['name'];
        }
        $this->view->assign('vo', $vo);
        $this->view->fetch('edit');
    }

    /**
     * @return string
     * @throws Exception 二级分类选择
     *
     */
    public function second_select(){
        $param = $this->request->param();
        $service = new TypeService();//数据处理
        $service->searchPage($this->view,$param);
        return $this->view->fetch();
    }

    public function secondTop(){
        $param = $this->request->param();
        $service = new TypeService();//数据处理
        $service->topList($this->view,$param);
        return $this->view->fetch();
    }

    public function topAdd(){
        $param = $this->request->param();
        $service = new TypeService();//数据处理
        try {
            if($service->topAdd(@$param['tIds'])){
                return  apiSuccess();
            }
            return ajax_return_adv('添加失败');
        }catch (Exception $e){
            return ajax_return_adv($e->getMessage());
        }
    }

    public function topDelete(){
        $param = $this->request->param();
        $service = new TypeService();//数据处理
        if(empty($param['id'])) return ajax_return_adv_error('请先选择');
        if($service->topDelete(@$param['id'])){
            return ajax_return_adv_error('删除失败', '');
        }
        return ajax_return_adv('删除成功', '');
    }

}